package com.biz.storage.util;

import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import lombok.*;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.io.*;

/**
 * @Description
 *      ailiyunOSS工具
 * @Author liuxi
 * @Date 2024/4/27
 **/
@Component
public class AliyunOssUtil {

    @Resource
    @Lazy
    private OSS ossClient;

    /**
     * 创建bucket
     */
    @SneakyThrows
    public void createBucket(String bucket) {
        boolean exist = ossClient.doesBucketExist(bucket);
        if (!exist) {
            ossClient.createBucket(bucket);
        }
    }

    /**
     * 文件上传
     */
    @SneakyThrows
    public void uploadFile(InputStream inputStream, String bucket, String objectName) {
        ossClient.putObject(bucket, objectName, inputStream);
    }

    /**
     * 文件下载
     */
    @SneakyThrows
    public InputStream downloadFile(String objectName, String bucket) {
        OSSObject ossObject = ossClient.getObject(bucket, objectName);
        return ossObject.getObjectContent();
    }

    @SneakyThrows
    public void deleteObject(String bucket, String objectName) {
        ossClient.deleteObject(bucket, objectName);
    }
}
